package com.xin.bi.manager;

import com.xin.bi.exception.BusinessException;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * redission限流
 */
@Service
public class RedisLimterManager {
    @Resource
    private RedissonClient redissonClient;

    public void doRateLimit(String key){
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);
        //每rateinterval允许rate个
        rateLimiter.trySetRate(RateType.OVERALL,2,1, RateIntervalUnit.SECONDS);
        boolean b = rateLimiter.tryAcquire(1);
        if(!b){
            throw new BusinessException("稍后再访问");
        }
    }
}
